package com.controller;


import com.model.*;
import com.response.Result;
import com.response.ResultGenerator;
import com.service.FaceService;
import com.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;



import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.client.RestTemplate;


@RestController
public class FaceController {
    private static Logger logger = LoggerFactory.getLogger(FaceController.class);

    private static String pass = "itworks";


    @Autowired
    FaceService faceService;

    public static CreateFaceResultVO errorAddFace = new CreateFaceResultVO();
    public static AddFaceResultVO addFaceResultVO = new AddFaceResultVO();
    public static SearchFaceResultVO searchFaceResultVO = new SearchFaceResultVO();
    static {
        errorAddFace.setErrmsg("1");
        errorAddFace.setError(1);
        addFaceResultVO.setErrmsg("1");
        addFaceResultVO.setError(1);
        searchFaceResultVO.setErrmsg("1");
        searchFaceResultVO.setError(1);
    }

    @PostMapping("/addFace")
    public CreateFaceResultVO addUser(@RequestParam("shopId")Integer shopId,
                                      @RequestParam("customerId")String customerId,
                                      @RequestParam("filepath")String filepath) throws Exception {
        if (customerId.contains("_")) {
            customerId = customerId.split("_")[1];
        }

        String faceId = faceService.addFace(filepath, Integer.valueOf(customerId), shopId);

        if (StringUtils.hasText(faceId)) {
            CreateFaceResultVO createFaceResultVO = new CreateFaceResultVO();
            createFaceResultVO.setErrmsg("0");
            createFaceResultVO.setData(new ArrayList<>());
            createFaceResultVO.getData().add(new AddFaceResultDetailVO());
            createFaceResultVO.getData().get(0).setFaceid(faceId);
            return createFaceResultVO;
        }
        return errorAddFace;
    }

    @PostMapping("/delFace")
    public AddFaceResultVO delFace(@RequestParam("shopId")Integer shopId,
                                      @RequestParam("customerId")String customerId,
                                      @RequestParam("faceId")String faceId) throws Exception {
        if (customerId.contains("_")) {
            customerId = customerId.split("_")[1];
        }
        faceService.deleteFace(Integer.valueOf(customerId), faceId, shopId);

        AddFaceResultVO addFaceResultVO = new AddFaceResultVO();
        addFaceResultVO.setErrmsg("0");
        addFaceResultVO.setError(0);
        return addFaceResultVO;
    }

    @PostMapping("/delPerson")
    public AddFaceResultVO delPerson(@RequestParam("shopId")Integer shopId,
                                      @RequestParam("customerId")String customerId) throws Exception {
        if (customerId.contains("_")) {
            customerId = customerId.split("_")[1];
        }

        faceService.deletePerson(Integer.valueOf(customerId), shopId);

        AddFaceResultVO addFaceResultVO = new AddFaceResultVO();
        addFaceResultVO.setErrmsg("0");
        addFaceResultVO.setError(0);
        return addFaceResultVO;
    }


    @PostMapping("/searchFace")
    public SearchFaceResultVO searchFace(@RequestParam("shopId")Integer shopId,
                                      @RequestParam("filepath")String filepath) throws Exception {
        String personId = faceService.searchFacesFromMultiple(filepath);

        if (personId != null) {
            SearchFaceResultVO result = new SearchFaceResultVO();
            SearchFaceResultDetailVO detailVO = new SearchFaceResultDetailVO();
            detailVO.setC("95");
            detailVO.setLabel(personId);

            result.setErrmsg("0");
            result.setData(new ArrayList<>());
            result.getData().add(detailVO);
            return result;
        }

        return searchFaceResultVO;
    }


    @PostMapping("/detectFace")
    public AddFaceResultVO detectFace(
                                      @RequestParam("filepath")String filepath) throws Exception {
        boolean result = faceService.detectFace(filepath);

        if (result) {
            AddFaceResultVO addFaceResultVO = new AddFaceResultVO();
            addFaceResultVO.setErrmsg("0");
            addFaceResultVO.setError(0);

            return addFaceResultVO;
        }

        return addFaceResultVO;
    }


    @GetMapping("/temp")
    public String temp()throws Exception{
        addIntranetFace();
        return "ok";
    }

    @GetMapping("/temp2")
    public String temp2()throws Exception{
        addIntranetFace2();
        return "ok";
    }

    public Map<String, String> getUserId() throws Exception{
        String filepath = "/data/html/cc.txt";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filepath));

        String line = bufferedReader.readLine().trim();

        Map<String, String> map = new HashMap<>();
        while (StringUtils.hasText(line)) {
            String temp[] = line.split(",");

            String customerId = temp[0].replaceAll("'", "");

            String cardNo = temp[1];

            cardNo = cardNo.split("'")[1];

            System.out.println("cardNo=" + cardNo + ",customer=" + customerId);
            map.put(cardNo, customerId);
            line = bufferedReader.readLine();
        }

        return map;
    }
    public void addIntranetFace() throws Exception{

        Map<String, String> map = getUserId();
//        String filePath = "/data/html/cc.xlsx";
        String filePath = "/Users/jay/IdeaProjects/binguo/LocalFaceRec/src/main/resources/static/cc.xlsx";
        InputStream is;
        Workbook wb;
        try {
            is = new FileInputStream(filePath);
            wb = new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);
            sheet = withoutRowEmpty(sheet);
            Row row;
            Cell cell;
            Integer rowNum = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < rowNum; i++) {
                row = sheet.getRow(i);
                cell = row.getCell(0);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String phone = cell.getStringCellValue();
                cell = row.getCell(1);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String name = cell.getStringCellValue();
                cell = row.getCell(2);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String picPath = cell.getStringCellValue();
//                Customer customer = customerService.getCustomerByPhone(phone);
                /*Customer customer = new Customer();
                customer.setPhone(phone);
                customer.setName(name);
                customerRepository.save(customer);
                CustomerExtend customerExtend = new CustomerExtend();
                customerExtend.setIsAudit(1);
                customerExtend.setCustomerId(customer.getId());
                customerExtend.setShopId(250);
                customerExtend.setUserStatus(1);
                customerExtend.setGroupId(0);
                customerExtend.setGroupName("普通会员");
                customerExtendRepository.save(customerExtend);
                PayCard payCard = new PayCard();
                payCard.setCardno(phone);
                payCard.setDeleted(false);
                payCard.setShopid(250);
                payCard.setCustomerid(customer.getId());
                payCard.setName("民生银行卡");
                payCard.setCardtype(new Byte("0"));
                payCard.setIsmaster(true);
                payCard.setIsnopasswordpay(true);
                payCard.setCreated(new Date());
                payCard.setUpdated(new Date());
                payCardRepository.save(payCard);*/

                if (StringUtils.hasText(picPath)) {

                    HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
                    MediaType jsontype = MediaType.APPLICATION_JSON;
                    DEFAULT_JSON_HEADER.setContentType(jsontype);
                    DEFAULT_JSON_HEADER.add("Accept", MediaType.APPLICATION_JSON.toString());


                    String imgUrl = "/data/html/images/faces/temp/"+picPath;

                    CmsCreate param = new CmsCreate();
                    param.setShopId("250");
                    param.setCustomerId(map.get(phone));
                    param.setFaceUrl(imgUrl);
                    logger.info("postParam :" + JsonUtil.toJson(param));
                    HttpEntity<String> entity = new HttpEntity<String>(JsonUtil.toJson(param), DEFAULT_JSON_HEADER);
                    ResponseEntity<String> resp = new RestTemplate().postForEntity("http://195.30.8.55/api/wxapp/face/cmsCreate", entity, String.class);
                    logger.info(resp.getBody());
                }

//                try {0000176244 .JPG
////                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addIntranetFace2() throws Exception{

        Map<String, String> map = getUserId();
        String filePath = "/data/html/cc2.xlsx";
        InputStream is;
        Workbook wb;
        try {
            is = new FileInputStream(filePath);
            wb = new XSSFWorkbook(is);
            Sheet sheet = wb.getSheetAt(0);
            sheet = withoutRowEmpty(sheet);
            Row row;
            Cell cell;
            Integer rowNum = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < rowNum; i++) {
                row = sheet.getRow(i);
                cell = row.getCell(0);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String phone = cell.getStringCellValue();
                cell = row.getCell(1);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String name = cell.getStringCellValue();
                cell = row.getCell(2);
                cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                String picPath = cell.getStringCellValue();
//                Customer customer = customerService.getCustomerByPhone(phone);
                /*Customer customer = new Customer();
                customer.setPhone(phone);
                customer.setName(name);
                customerRepository.save(customer);
                CustomerExtend customerExtend = new CustomerExtend();
                customerExtend.setIsAudit(1);
                customerExtend.setCustomerId(customer.getId());
                customerExtend.setShopId(250);
                customerExtend.setUserStatus(1);
                customerExtend.setGroupId(0);
                customerExtend.setGroupName("普通会员");
                customerExtendRepository.save(customerExtend);
                PayCard payCard = new PayCard();
                payCard.setCardno(phone);
                payCard.setDeleted(false);
                payCard.setShopid(250);
                payCard.setCustomerid(customer.getId());
                payCard.setName("民生银行卡");
                payCard.setCardtype(new Byte("0"));
                payCard.setIsmaster(true);
                payCard.setIsnopasswordpay(true);
                payCard.setCreated(new Date());
                payCard.setUpdated(new Date());
                payCardRepository.save(payCard);*/

                if (StringUtils.hasText(picPath)) {

                    HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
                    MediaType jsontype = MediaType.APPLICATION_JSON;
                    DEFAULT_JSON_HEADER.setContentType(jsontype);
                    DEFAULT_JSON_HEADER.add("Accept", MediaType.APPLICATION_JSON.toString());


                    String imgUrl = "/data/html/images/faces/temp2/"+picPath;

                    CmsCreate param = new CmsCreate();
                    param.setShopId("250");
                    param.setCustomerId(map.get(phone));
                    param.setFaceUrl(imgUrl);
                    logger.info("postParam :" + JsonUtil.toJson(param));
                    HttpEntity<String> entity = new HttpEntity<String>(JsonUtil.toJson(param), DEFAULT_JSON_HEADER);
                    ResponseEntity<String> resp = new RestTemplate().postForEntity("http://195.30.8.55/api/wxapp/face/cmsCreate", entity, String.class);
                    logger.info(resp.getBody());
                }

//                try {0000176244 .JPG
////                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Sheet withoutRowEmpty(Sheet sheet){
        boolean flag;
        for (int i = 1; i <= sheet.getLastRowNum();) {
            Row r = sheet.getRow(i);
            if(r == null){
                // 如果是空行（即没有任何数据、格式），直接把它以下的数据往上移动
                sheet.shiftRows(i+1, sheet.getLastRowNum(),-1);
                continue;
            }
            flag = false;
            for(Cell c:r){
                if(c.getCellType() != Cell.CELL_TYPE_BLANK){
                    flag = true;
                    break;
                }
            }
            if(flag){
                i++;
                continue;
            }
            else{//如果是空白行（即可能没有数据，但是有一定格式）
                if(i == sheet.getLastRowNum()) {
                    //如果到了最后一行，直接将那一行remove掉
                    sheet.removeRow(r);
                } else{
                    //如果还没到最后一行，则数据往上移一行
                    sheet.shiftRows(i+1, sheet.getLastRowNum(),-1);
                }
            }
        }
        System.out.println("总行数："+(sheet.getLastRowNum()+1));
        return sheet;
    }
}
